package net.ceviz.forum.java;

import java.util.ArrayList;
import java.util.List;

public class Citizen {

	private int citizenNumber;
	private String name;

	private static final List<Citizen> CITIZENS = new ArrayList<Citizen>();

	private Citizen(int citizenNumber, String name) {
		super();
		this.citizenNumber = citizenNumber;
		this.name = name;
	}

	public static Citizen createCitizen(int citizenNumber, String name) {
		Citizen newCitizen = new Citizen(citizenNumber, name);
		synchronized (Citizen.class) {
			for (Citizen resource : CITIZENS) {
				if (resource.equals(newCitizen)) {
					return resource;
				}
			}
			CITIZENS.add(newCitizen);
		}
		
		return newCitizen;
	}
	
	public static boolean removeCitizen(Citizen citizen) {
		if (citizen != null) {
			synchronized (Citizen.class) {
				return CITIZENS.remove(citizen);
			}
		}
		else {
			throw new IllegalArgumentException("Citizen instance cannot be null.");
		}
	}
	
	public static boolean isCitizenExists(Citizen citizen) {
		if (citizen != null) {
			synchronized (Citizen.class) {
				return CITIZENS.contains(citizen);
			}
		}
		
		return false;
	}
	
	public static int numberOfCitizens() {
		synchronized (Citizen.class) {
			return CITIZENS.size();
		}
	}

	public int getCitizenNumber() {
		return citizenNumber;
	}

	public void setCitizenNumber(int citizenNumber) {
		this.citizenNumber = citizenNumber;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object obj) {
		// citizenNumber' s are unique
		if (obj instanceof Citizen) {
			Citizen other = (Citizen) obj;
			if (other.citizenNumber == this.citizenNumber) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	@Override
	public String toString() {
		return "Citizen [citizenNumber=" + citizenNumber + ", name=" + name
				+ "]";
	}
	

}
